package com.tboss.template.common.springSecurity;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

public class LoginFailureProcess implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest req,
			HttpServletResponse res, AuthenticationException auth) throws IOException, ServletException {

		String url = "/template/auth/login";
		String referer = req.getHeader("Referer");
		if(referer != null && referer.indexOf("/template/auth/authConfirm") != -1){
			url = "/auth/authConfirm";
			String j_username = req.getParameter("j_username");
			req.setAttribute("username", (j_username.indexOf(";") != -1)?j_username.split(";")[0]:j_username);
		}
		
		//req.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", auth);
		req.setAttribute("error", auth.getMessage());
		RequestDispatcher dispatcher = req.getRequestDispatcher(url);
		dispatcher.forward(req, res);
	}

}
